﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WebSocketSharp.Server;
using WebSocketSharp;
using WebSocketSharp.Net;
using System.Configuration;
using Newtonsoft.Json;
using FluentScheduler;
using System.IO;
using System.Net;
using HtmlAgilityPack;
using System.Diagnostics;
using WssServer.Helper;
using Model;
using WssServer.Excel;
using WssServer.Domain;

namespace WssServer
{
    public partial class frmMain : Form
    {

        public frmMain()
        {
            InitializeComponent();
            this.FormClosing += FrmMain_FormClosing;
            StartService();
            Text = $"报表打印服务器(Ver:{GVar.ver})";
            MainNotifyIcon.Text = MainNotifyIcon.BalloonTipText = MainNotifyIcon.BalloonTipTitle = Text;
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        /// <summary>
        /// 服务器启动
        /// </summary>
        private void StartService()
        {
            GVar.httpsv = new HttpServer(2629);
            GVar.httpsv.DocumentRootPath = ConfigurationManager.AppSettings["DocumentRootPath"];         
            GVar.httpsv.OnGet += (sender, e) =>
            {
                var req = e.Request;
                var res = e.Response;

                var path = req.RawUrl;
                if (path == "/")
                    path += "index.html";

                byte[] contents;
                if (!e.TryReadFile(path, out contents))
                {
                    res.StatusCode = (int)WebSocketSharp.Net.HttpStatusCode.NotFound;
                    return;
                }

                if (path.EndsWith(".html"))
                {
                    res.ContentType = "text/html";
                    res.ContentEncoding = Encoding.UTF8;
                }
                else if (path.EndsWith(".js"))
                {
                    res.ContentType = "application/javascript";
                    res.ContentEncoding = Encoding.UTF8;
                }

                res.WriteContent(contents);
            };
            GVar.httpsv.AddWebSocketService<PrinterSrv>("/PrinterSrv");
            GVar.httpsv.Start();
            LogHelper.Info("服务器启动！");
        }
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }

        private void MainNotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (GVar.ShowYNCMessage("确定退出吗?") == DialogResult.Yes)
            {
                GVar.httpsv.Stop();
                JobManager.RemoveAllJobs();
                LogHelper.Info("服务器关闭！");
                Application.ExitThread();
            }
        }

        /// <summary>
        /// 判断文件是否被占用
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public bool IsFileInUse(string fileName)
        {
            bool inUse = true;
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read,
                FileShare.None);
                inUse = false;
            }
            catch
            {
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
            return inUse;//true表示正在使用,false没有使用    
        }
        private void 重启ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainNotifyIcon.BalloonTipText = "服务器重新启动中……";
            GVar.httpsv.Stop();

            LogHelper.Info("服务器关闭！");
            MainNotifyIcon.ShowBalloonTip(2000);
            StartService();

        }

        private void 查看日志ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string FileName = System.IO.Path.Combine(Environment.CurrentDirectory, @"Log");
            System.Diagnostics.Process.Start("Explorer.exe", FileName);
        }


        private void 退出ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            GVar.httpsv.Stop();
            JobManager.RemoveAllJobs();
            LogHelper.Info("服务器关闭！");
            Application.ExitThread();
        }

        private void button1_Click(object sender, EventArgs e)
        {
           
        }
        private void label1_Click(object sender, EventArgs e)
        {

        }
    }
    
}
